package com.iasku.iaskueleclass_phone.activity;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;

import com.iasku.constant.Constant;
import com.iasku.fragment.CourseFragment;
import com.iasku.fragment.ErrorbookFragment;
import com.iasku.fragment.HomeworkFragment;
import com.iasku.fragment.StatisticsFragment;
import com.iasku.iaskueleclass_phone.R;
import com.iasku.manager.ExitManager;
import com.iasku.manager.IaskuManager;
import com.iasku.manager.ViewManager;
import com.iasku.util.IaskuUtil;

public class MainActivity extends BaseActivity {
    //定义Fragment切换对象
    private FragmentTabHost mTabHost;

    // 定义一个布局
    private LayoutInflater mLayoutInflater;
    
    private static final Class[] mFragmentClasses = {HomeworkFragment.class,StatisticsFragment.class,
                                                        ErrorbookFragment.class,CourseFragment.class};
    
    private static final int[] mImageViewArray = { R.drawable.main_tab_corrected, R.drawable.main_tab_count,
            R.drawable.main_tab_error,R.drawable.main_tab_course };
    
    private static final int[] mTextviewColorArray = { R.color.main_bottom_blue, R.color.main_bottom_green,
        R.color.main_bottom_blue,R.color.main_bottom_orange};
    
    private String[] mTabTextArray;
    
    private static boolean isExit;
    private static Toast toast;
    private static final int EXIT_TIME = 3000;
    
    private void initView(){
        Constant.SCHOOL_INFO_CONTENT = getIntent().getStringExtra(Constant.SCHOOL_INFO);
        String userInfo = getIntent().getStringExtra(Constant.USER_LOGIN_INFO);
        if (userInfo != null && !"".equals(userInfo)) {
            String[] arr = userInfo.split(":");
            Constant.USER_IASKUNAME = arr[0];
            Constant.USER_TRUENAME = arr[5];
        }
        
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        mLayoutInflater = LayoutInflater.from(this);
        // 得到fragment的个数
        mTabTextArray = getResources().getStringArray(R.array.main_tab_text);
        for (int i = 0; i < mFragmentClasses.length; i++) {
            // 为每一个Tab按钮设置图标、文字和内容
            TabSpec tabSpec = mTabHost.newTabSpec(mTabTextArray[i]).setIndicator(getTabItemView(i));
            // 将Tab按钮添加进Tab选项卡中
            mTabHost.addTab(tabSpec, mFragmentClasses[i], null);
            // 设置Tab按钮的背景
            mTabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.color.white);
        }
    }
    
    private View getTabItemView(int index) {
        View view = mLayoutInflater.inflate(R.layout.main_tab_item, null);

        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        imageView.setImageResource(mImageViewArray[index]);

        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(mTabTextArray[index]);
        textView.setTextColor(getResources().getColor(mTextviewColorArray[index]));
        return view;
    }
    
    /** 初始化日期 */
    private void initDate() {
        Date now_end = new Date();
        GregorianCalendar cal_start = new GregorianCalendar();
        cal_start.setTime(now_end);
        cal_start.add(GregorianCalendar.DATE, -7);
        Constant.YEAR_START = cal_start.get(Calendar.YEAR);
        Constant.MONTH_START = cal_start.get(Calendar.MONTH);
        Constant.DAY_START = cal_start.get(Calendar.DAY_OF_MONTH);
        Calendar cal_end = Calendar.getInstance();
        Constant.YEAR_END = cal_end.get(Calendar.YEAR);
        Constant.MONTH_END = cal_end.get(Calendar.MONTH);
        Constant.DAY_END = cal_end.get(Calendar.DAY_OF_MONTH);
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_tab_layout);
        IaskuManager.getInstance().setContext(this);
        IaskuManager.getInstance().setSubjectId(0);
        ExitManager.getExitManager().addActivity(this);
        initDate();
        initView();
        IaskuUtil.parserSchoolInfo(Constant.SCHOOL_INFO_CONTENT);
    }
    
    @Override
    public void onBackPressed() {
        WebView webview = ViewManager.getInstance().getWebview();
        if(webview != null){
            if(webview.canGoBack()){
                webview.goBack();
            }else{
                goToExit();
            }
        }else{
            goToExit();
        }
    }
    
    private void goToExit(){
        if (!isExit) {// 第一次按下返回键
            isExit = true;// 退出标志位设置成true
            toast = Toast.makeText(this, Constant.EXIT_MSG, EXIT_TIME);// 向用户提示
            toast.show();
            // 一个Timer()对象，如果用户在第一次按返回键两秒后没有再按一次返回键退出，表示用户取消了操作，则重新将标志位设置成false
            new Thread() {
                public void run() {
                    while (isExit) {
                        try {
                            Thread.sleep(2000);
                            isExit = false;
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        } else {
            // 退出程序
            toast.cancel();
            MainActivity.super.finish();
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }
}
